package top.ruanlitao.shortlink.project.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import top.ruanlitao.shortlink.project.common.constant.SentinelRuleResourceConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化限流配置
 */
@Component
@RequiredArgsConstructor
public class SentinelRuleConfig implements InitializingBean {

    private final SentinelRuleCountConfiguration sentinelRuleCountConfiguration;

    @Override
    public void afterPropertiesSet() {
        List<FlowRule> rules = new ArrayList<>();

        // 创建短链接限流规则
        FlowRule createOrderRule = new FlowRule();
        // 设置资源名称（标识需要限流的接口或方法）
        createOrderRule.setResource(SentinelRuleResourceConstant.CREATE_LINK);
        // 设置限流类型为 QPS（每秒请求数）
        createOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 从配置中读取 QPS 阈值
        createOrderRule.setCount(sentinelRuleCountConfiguration.getCreateShortLinkQps());
        // 将规则添加到列表
        rules.add(createOrderRule);

        // 访问短链接限流规则
        FlowRule gotoOrderRule = new FlowRule();
        gotoOrderRule.setResource(SentinelRuleResourceConstant.GOTO_LINK);
        gotoOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        gotoOrderRule.setCount(sentinelRuleCountConfiguration.getGotoShortLinkQps());
        rules.add(gotoOrderRule);

        FlowRuleManager.loadRules(rules);
    }
}